<template>
	<view class="page-container">
		<!-- 顶部导航 -->
		<view class="status-bar" :style="{ height: navHeight + 'px', 'padding-top': statusBarHeight + 'px', }">
			<view class="nav-bar">
				<view class="navbar-left"></view>
				<view class="navbar-title">消息</view>
				<view class="navbar-right" @click="add_message">
					<image src="/static/plus-circle.png" class="nav-icon" />
				</view>
			</view>
		</view>
		<view class="status-height-color" :style="{ height: navHeight + 'px', 'padding-top': statusBarHeight + 'px' }">
		</view>
		<scroll-view class="main-sroll-view" scroll-y :scroll-with-animation="true" :enhanced="true" :bounces="true"
			:show-scrollbar="false" :style="{ height: scrollViewHeight }" @scroll="onContainerScroll"
			@scrolltolower="onScrollToLower">
			<!-- 搜索框 -->
			<!-- <view class="search-container">
        <view class="search-box">
          <image class="search-icon" src="/static/search_icon.png" />
          <input class="search-input" v-model="searchValue" placeholder="搜索" confirm-type="search" />
          <image v-if="searchValue" class="clear-icon" src="/static/clear.png" @click="clearSearch" />
        </view>
      </view> -->
			<!-- 消息列表 -->
			<view class="message-list-container">
				<view class="message-list">
					<view class="message-item" v-for="(item, index) in messageList" :key="item.id || index"
						@click="onMessageClick(item)">

						<!-- 左侧头像 -->
						<view class="message-avatar-wrapper">
							<!-- 红点标记 -->
							<view v-if="item.hasRedDot" class="red-dot"></view>
							<!-- 实际显示的头像 -->
							<view class="message-avatar"
								:style="{ backgroundImage: `url(${getAvatarUrl(item.avatar) || '/static/default_avatar.png'})` }"
								:class="{ 'loaded': item.avatarLoaded }">
							</view>

							<!-- 隐藏的image标签用于监听加载事件 -->
							<image class="hidden-avatar-image" :src="getAvatarUrl(item.avatar) || '/static/default_avatar.png'"
								@load="onAvatarLoad(index)" @error="onAvatarError(index)" />

							<!-- 加载动画 - 只在未加载完成时显示 -->
							<view class="avatar-loading" v-if="!item.avatarLoaded">
								<view class="avatar-loading-spinner"></view>
							</view>

							<!-- 移除骨架屏，简化渲染流程 -->
						</view>

						<!-- 中间内容区域 -->
						<view class="message-content">
							<view class="message-title-row">
								<text class="message-title">{{ item.title }}</text>
								<text class="message-date">{{ item.date }}</text>
							</view>
							<text class="message-desc">{{ item.description }}</text>
						</view>
					</view>
				</view>

				<!-- 加载状态 -->
				<view class="loading-more" v-if="messageLoading">
					<view class="loading-spinner"></view>
					<text class="loading-text">加载中...</text>
				</view>

				<!-- 无数据状态 -->
				<view class="empty-message" v-if="!messageLoading && messageList.length === 0">
					<image class="empty-img" src="/static/empty_state.png" />
					<text class="empty-text">暂无消息</text>
				</view>
			</view>


			<!-- 弹窗菜单 -->
			<view class="popup-menu" v-if="showPopupMenu" @click="hidePopupMenu"
				:class="{ 'android-popup': isAndroid, 'ios-popup': isIOS }">
				<!-- 添加遮罩层 -->
				<view class="popup-mask" @click="hidePopupMenu"></view>
				<view class="popup-content" @click.stop :class="{ 'android-content': isAndroid, 'ios-content': isIOS }"
					:style="{ top: popupTopPosition }">
					<!-- 弹窗箭头 -->
					<view class="popup-arrow" :class="{ 'android-arrow': isAndroid, 'ios-arrow': isIOS }"
						:style="{ right: arrowRightPosition, top: '-10rpx' }"></view>
					<!-- 菜单项 -->
					<view class="menu-item" @click="onAddFriend">
						<image src="/static/add-firend.png" class="menu-icon" />
						<text class="menu-text">添加好友</text>
					</view>
					<view class="menu-item" @click="onMyFriends">
						<view class="menu-icon-wrapper">
							<image src="/static/address-book.png" class="menu-icon" />
							<!-- 我的好友红点 -->
							<view class="menu-red-dot" v-if="showFriendRedDot"></view>
						</view>
						<text class="menu-text">我的好友</text>
					</view>
					<view class="menu-item" @click="onGroupChat">
						<image src="/static/group-chat.png" class="menu-icon group-chat-icon" />
						<text class="menu-text">工作组</text>
					</view>
				</view>
			</view>


		</scroll-view>

		<!-- 添加好友输入框弹窗 -->
		<view class="add-friend-modal" v-if="showAddFriendModal" @click="hideAddFriendModal">
			<view class="add-friend-content" @click.stop>
				<view class="modal-header">
					<text class="modal-title">添加好友</text>
					<view class="close-btn" @click="hideAddFriendModal">
						<text class="close-icon">×</text>
					</view>
				</view>
				<view class="modal-body">
					<view class="input-group">
						<input class="phone-input" v-model="phoneNumber" placeholder="请输入手机号或邀请码" maxlength="20"
							@input="validatePhone" @blur="validatePhone" />
						<view class="error-tip" v-if="phoneError">{{ phoneError }}</view>
					</view>
				</view>
				<view class="modal-footer">
					<button class="confirm-btn" :class="{ 'disabled': !isPhoneValid }" :disabled="!isPhoneValid"
						@click="confirmAddFriend">
						确定
					</button>
				</view>
			</view>
		</view>

		<!-- 创建群聊弹窗 -->
		<tn-popup v-model="showCreateGroupModal" mode="bottom" height="95%" :borderRadius="20" :maskCloseable="true"
			backgroundColor="#2c2c2e">
			<view class="create-group-content">
				<view class="modal-header">
					<!-- iOS安全区域适配 -->
					<view class="modal-header-content">
						<text class="modal-title">创建工作组</text>
						<view class="close-btn" @click="hideCreateGroupModal">
							<text class="close-icon">×</text>
						</view>
					</view>
				</view>

				<view class="modal-body">
					<!-- 群聊名称输入 -->
					<view class="input-group">
						<text class="input-label">工作组名称</text>
						<input class="group-name-input" v-model="groupName" placeholder="请输入工作组名称" maxlength="20" />
					</view>

					<!-- 联系人列表 -->
					<view class="contact-list-section">
						<view class="section-header">
							<text class="section-title">选择联系人</text>
							<text class="selected-count">已选择 {{ selectedContacts.length }} 人</text>
						</view>

						<scroll-view class="contact-list" scroll-y>
							<view class="contact-item" v-for="(contact, index) in contactList" :key="contact.id || index"
								@click="toggleContactSelection(contact)">
								<!-- 单选按钮 -->
								<view class="radio-btn" :class="{ 'selected': isContactSelected(contact) }">
									<view class="radio-inner" v-if="isContactSelected(contact)">
										<text class="checkmark">✓</text>
									</view>
								</view>

								<!-- 头像 -->
								<view class="contact-avatar">
									<image :src="getAvatarUrl(contact.avatar) || '/static/default_avatar.jpg'" class="avatar-img" />
								</view>

								<!-- 联系人信息 -->
								<view class="contact-info">
									<text class="contact-name">{{ contact.name }}</text>
									<!-- <text class="contact-phone" v-if="contact.phone">{{ contact.phone }}</text> -->
								</view>
							</view>
						</scroll-view>
					</view>
				</view>

				<view class="modal-footer">
					<button class="confirm-btn" :class="{ 'disabled': selectedContacts.length < 2 }"
						:disabled="selectedContacts.length < 2" @click="confirmCreateGroup">
						创建工作组 ({{ selectedContacts.length }}人)
					</button>
				</view>
			</view>
		</tn-popup>
	</view>
</template>

<script>
export default {
	data() {
		return {
			navHeight: "", //整体顶部导航栏的高度
			statusBarHeight: "", //状态栏高度
			searchValue: '', //搜索框的值
			messageList: [], //消息列表，从接口获取
			messageLoading: false, //消息加载状态
			scrollViewHeight: 0, // 滚动视图高度
			showPopupMenu: false, // 是否显示弹窗菜单
			showAddFriendModal: false, // 是否显示添加好友输入框弹窗
			phoneNumber: '', // 手机号输入框的值
			phoneError: '', // 手机号错误提示
			isPhoneValid: false, // 手机号是否有效
			showCreateGroupModal: false, // 是否显示创建群聊弹窗
			groupName: '', // 群聊名称输入框的值
			contactList: [], // 联系人列表，从接口获取
			selectedContacts: [],

			// 添加好友红点
			showFriendRedDot: false,

			// 系统信息
			systemInfo: {}, // 系统信息
			isIOS: false, // 是否为iOS系统
			isAndroid: false, // 是否为Android系统
			safeAreaTop: 0, // 顶部安全区域高度

			// 消息同步相关
			syncTimer: null, // 消息同步定时器
			syncInterval: 2500, // 同步间隔，2.5秒
			lastSyncTime: 0,
			isPageActive: true,
			lastMessageData: null,
			refreshFlag: 0, // 添加强制刷新标志

			// 弹窗菜单位置相关
			popupTopPosition: '0px', // 弹窗内容距离顶部的高度
			arrowRightPosition: '0px', // 箭头距离右侧的距离
		}
	},
	created() {
		//获取手机系统的信息（主要是获取状态栏和胶囊的高度）
		let {
			statusBarHeight,
			system
		} = uni.getSystemInfoSync()
		this.statusBarHeight = statusBarHeight
		this.navHeight = statusBarHeight + (system.indexOf("iOS") > -1 ? 44 : 48)

		// 获取系统信息
		this.getSystemInfo();

		// 计算滚动视图高度
		this.calculateScrollViewHeight();
		
		// 初始化弹窗位置变量
		this.popupTopPosition = (this.navHeight - 15) + 'px';
		this.arrowRightPosition = this.isIOS ? '24rpx' : '18rpx';
	},
	onLoad() {
		let userInfo = uni.getStorageSync('userInfo');
		const userid = userInfo?.data?.userid || userInfo?.userid || '';
		// 加载消息列表
		this.loadMessageList();
		// 启动消息同步
		this.startMessageSync();
	},

	mounted() {
		// 确保数据加载
		if (this.messageList.length === 0) {
			this.loadMessageList();
		}
		// 监听用户操作事件
		this.bindUserInteractionEvents();

		// 使用同样的自适应机制
		this.mountedTimer = setInterval(() => {
			if (this.isPageActive) {
				this.syncMessages();
			}
		}, this.syncInterval);

		// 添加页面可见性变化监听
		this.setupVisibilityListener();
	},

	onShow() {
		// 页面显示时立即同步一次
		this.syncMessages();
		// 重新启动同步
		this.startMessageSync();
		// 从聊天页面返回时，重新加载消息列表以更新红点状态
		// this.loadMessageList(); // 注释掉这行，防止重复加载
	},

	onHide() {
		// 页面隐藏时停止同步
		this.stopMessageSync();
	},

	onUnload() {
		// 页面卸载时清理
		this.stopMessageSync();
		this.unbindUserInteractionEvents();

		if (this.mountedTimer) {
			clearInterval(this.mountedTimer);
		}

		// #ifdef H5
		document.removeEventListener('visibilitychange', this.handleVisibilityChange);
		// #endif

		// #ifdef APP-PLUS
		plus.globalEvent.removeEventListener('resume');
		plus.globalEvent.removeEventListener('pause');
		// #endif
	},
	methods: {
		// 加载消息列表
		async loadMessageList() {
			try {
				this.messageLoading = true;

				// 获取用户信息
				let userInfo = uni.getStorageSync('userInfo');
				const userid = userInfo?.data?.userid || userInfo?.userid || '';

				if (!userid) {
					uni.showToast({
						title: '用户信息获取失败',
						icon: 'none'
					});
					return;
				}

				// 调用获取消息列表接口
				const response = await this.$Request.postApi('/bot/api/agentcgetuserimmsg', { userid: userid });

				if (response.status === 1) {
					// 成功获取数据
					if (response.data && Array.isArray(response.data)) {
						// 保存原始数据用于后续比较
						this.lastMessageData = JSON.parse(JSON.stringify(response.data));

						// 处理接口返回的数据，转换为页面需要的格式
						this.messageList = response.data.map(item => {
							// 格式化时间戳为日期字符串
							const formatDate = (timestamp) => {
								if (!timestamp) return '2025/01/15';
								const date = new Date(timestamp * 1000);
								const year = date.getFullYear();
								const month = String(date.getMonth() + 1).padStart(2, '0');
								const day = String(date.getDate()).padStart(2, '0');
								return `${year}-${month}-${day}`;
							};

							return {
								id: item.id,
								title: item.name,
								date: formatDate(item.update_time),
								avatar: item.avatar || '/static/default_avatar.png',
								avatarLoaded: true, // 直接设为已加载，避免延迟问题
								hasRedDot: item.show_red === 1, // 根据show_red字段判断是否有红点（1有红点，0无红点）
								description: item.new_message,
								show_friendred: item.show_friendred || 0 // 保存好友红点状态
							};
						});

						// 检查show_friendred字段，如果有任何一项为1，则显示红点
						this.showFriendRedDot = response.data.some(item => item.show_friendred === 1);

						// 如果数组为空，则默认没有红点
						if (response.data.length === 0) {
							this.showFriendRedDot = false;
						}

						// 初始化同步时间
						this.lastSyncTime = Date.now();
					} else {
						this.messageList = [];
						this.showFriendRedDot = false;
					}
				} else {
					// 获取失败
					uni.showToast({
						title: response.message || '获取消息列表失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('获取消息列表失败:', error);
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
			} finally {
				this.messageLoading = false;
			}
		},

		// 头像加载成功
		onAvatarLoad(index) {
			if (this.messageList[index]) {
				this.$set(this.messageList[index], 'avatarLoaded', true);
			}
		},

		// 头像加载失败
		onAvatarError(index) {
			if (this.messageList[index]) {
				// 即使加载失败也设置为已加载，避免一直显示加载动画
				this.$set(this.messageList[index], 'avatarLoaded', true);
				// 将avatar设置为默认头像
				this.$set(this.messageList[index], 'avatar', '/static/default_avatar.png');
			}
		},

		// 获取头像URL
		getAvatarUrl(head) {
			if (!head) {
				return '/static/default_avatar.png'; // 默认头像
			}
			// 如果已经是完整url，直接返回
			if (/^https?:\/\//.test(head)) return head;
			// 防止多斜杠
			return 'https://tob.cycyai.com/' + head.replace(/^\/+/, '');
		},

		// 容器滚动事件
		onContainerScroll(e) {
			// 处理滚动事件
		},

		// 滚动到底部
		onScrollToLower() {
			// 这里可以添加加载更多数据的逻辑
			// this.loadMoreData();
		},

		// 刷新消息列表
		refreshMessageList() {
			this.loadMessageList();
		},

		// 点击消息项
		onMessageClick(item) {
			// 立即更新本地红点状态为已读
			if (item.hasRedDot) {
				const index = this.messageList.findIndex(msg => msg.id === item.id);
				if (index > -1) {
					this.$set(this.messageList[index], 'hasRedDot', false);

					// 尝试更新远程红点状态
					this.updateMessageReadStatus(item.id);
				}
			}

			uni.navigateTo({
				url: `/homePages/groupChat?groupid=${item.id}`
			})
		},

		// 清除搜索
		clearSearch() {
			this.searchValue = '';
		},

		// 获取系统信息
		getSystemInfo() {
			try {
				const systemInfo = uni.getSystemInfoSync();
				this.systemInfo = systemInfo;

				// 判断系统类型
				this.isIOS = systemInfo.platform === 'ios' || systemInfo.system.toLowerCase().includes('ios');
				this.isAndroid = systemInfo.platform === 'android' || systemInfo.system.toLowerCase().includes(
					'android');

				// 获取安全区域信息
				if (systemInfo.safeArea) {
					// 顶部安全区域高度（刘海屏、灵动岛等）
					this.safeAreaTop = systemInfo.safeArea.top;
				} else {
					this.safeAreaTop = 0;
				}


			} catch (error) {
				console.error('获取系统信息失败:', error);
				// 默认设置
				this.isAndroid = true;
				this.isIOS = false;
				this.safeAreaTop = 0;
			}
		},

		// 计算滚动视图高度
		calculateScrollViewHeight() {
			const {
				statusBarHeight,
				system
			} = uni.getSystemInfoSync();
			const navHeight = statusBarHeight + (system.indexOf("iOS") > -1 ? 44 : 48);
			this.scrollViewHeight = `calc(100vh - ${navHeight}px)`;
		},

		// 测试滚动到底部
		testScrollToBottom() {
			// 这里可以添加滚动到底部的逻辑
		},

		// 显示弹窗菜单
		add_message() {
			this.showPopupMenu = !this.showPopupMenu;
			
			if (this.showPopupMenu) {
				// 菜单打开时，动态计算位置
				this.$nextTick(() => {
					this.adjustPopupPosition();
				});
			}
		},
		
		// 新增：动态调整弹窗位置
		adjustPopupPosition() {
			try {
				// 获取当前系统信息
				const { statusBarHeight, system } = uni.getSystemInfoSync();
				const navHeight = statusBarHeight + (system.indexOf("iOS") > -1 ? 44 : 48);
				
				// 计算合适的top值：减小顶部距离，让菜单更靠近图标
				// 原来是navHeight + 10，现在改为navHeight - 15使菜单上移
				const topPosition = navHeight - 15; 
				
				// 使用uni的API设置样式变量，通过class来应用
				this.popupTopPosition = topPosition + 'px';
				this.arrowRightPosition = this.isIOS ? '24rpx' : '18rpx';
				
				// 强制更新视图
				this.$forceUpdate();
			} catch (e) {
				console.error('调整弹窗位置失败:', e);
			}
		},

		// 隐藏弹窗菜单
		hidePopupMenu() {
			this.showPopupMenu = false;
		},

		// 显示添加好友输入框弹窗
		showAddFriendInputModal() {
			this.showAddFriendModal = true;
			this.phoneNumber = '';
			this.phoneError = '';
			this.isPhoneValid = false;
			this.hidePopupMenu(); // 隐藏菜单弹窗
		},

		// 隐藏添加好友输入框弹窗
		hideAddFriendModal() {
			this.showAddFriendModal = false;
		},

		// 显示创建群聊弹窗
		async openCreateGroupModal() {
			this.showCreateGroupModal = true;
			this.groupName = '';
			this.selectedContacts = [];
			this.hidePopupMenu(); // 隐藏菜单弹窗

			// 如果联系人列表为空，则加载联系人数据
			if (this.contactList.length === 0) {
				await this.loadContactList();
			}
		},

		// 隐藏创建群聊弹窗
		hideCreateGroupModal() {
			this.showCreateGroupModal = false;
		},

		// 手机号或邀请码输入框输入事件
		validatePhone() {
			const input = this.phoneNumber.trim();
			if (!input) {
				this.phoneError = '输入不能为空';
				this.isPhoneValid = false;
				return;
			}
			
			// 判断是否为纯数字手机号
			const isPhoneNumber = /^\d+$/.test(input);
			
			if (isPhoneNumber) {
				// 手机号验证
				if (input.length !== 11) {
					this.phoneError = '手机号应为11位数字';
					this.isPhoneValid = false;
					return;
				}
				
				if (!/^1[3-9]\d{9}$/.test(input)) {
					this.phoneError = '请输入正确的手机号格式';
					this.isPhoneValid = false;
					return;
				}
			} else {
				// 邀请码验证（允许字母和数字的组合）
				if (!/^[a-zA-Z0-9]{3,20}$/.test(input)) {
					this.phoneError = '邀请码格式不正确';
					this.isPhoneValid = false;
					return;
				}
			}
			
			this.phoneError = '';
			this.isPhoneValid = true;
		},

		// 确认添加好友
		async confirmAddFriend() {
			if (!this.isPhoneValid) {
				uni.showToast({
					title: '请输入正确的手机号或邀请码',
					icon: 'none'
				});
				return;
			}

			try {
				// 显示加载提示
				uni.showLoading({
					title: '发送申请中...'
				});

				// 获取用户信息
				let userInfo = uni.getStorageSync('userInfo');
				const userid = userInfo?.data?.userid || userInfo?.userid || '';
				// 调用发送好友申请接口
				const response = await this.$Request.postApi('/bot/api/agentcadduserfriend', {
					userid: userid,
					telephone: this.phoneNumber
				});
				// 隐藏加载提示
				uni.hideLoading();
				if (response.status === 1) {
					// 成功发送申请
					uni.showToast({
						title: response.message || '申请发送成功',
						icon: 'none'
					});
					this.hideAddFriendModal();
				} else {
					// 发送失败
					uni.showToast({
						title: response.message || '申请发送失败',
						icon: 'none'
					});
				}
			} catch (error) {
				// 隐藏加载提示
				uni.hideLoading();
				console.error('发送好友申请失败:', error);
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
			}
		},

		// 添加好友
		onAddFriend() {
			this.showAddFriendInputModal();
		},

		// 发起群聊
		onGroupChat() {
			this.hidePopupMenu();
			this.openCreateGroupModal();
		},

		// 我的好友
		onMyFriends() {
			this.hidePopupMenu();
			uni.navigateTo({
				url: '/homePages/MyFriend'
			});
		},

		// 切换联系人选择状态
		toggleContactSelection(contact) {
			const index = this.selectedContacts.findIndex(item => item.id === contact.id);
			if (index > -1) {
				this.selectedContacts.splice(index, 1);
			} else {
				this.selectedContacts.push(contact);
			}
		},

		// 判断联系人是否已选择
		isContactSelected(contact) {
			return this.selectedContacts.some(item => item.id === contact.id);
		},

		// 加载联系人列表
		async loadContactList() {
			try {
				// 显示加载提示
				uni.showLoading({
					title: '加载联系人中...'
				});
				// 获取用户信息
				let userInfo = uni.getStorageSync('userInfo');
				const userid = userInfo?.data?.userid || userInfo?.userid || '';

				if (!userid) {
					uni.hideLoading();
					uni.showToast({
						title: '用户信息获取失败',
						icon: 'none'
					});
					return;
				}
				const response = await this.$Request.postApi('/bot/api/agentcgetmyuserfriendlist', {
					userid: userid
				});
				if (response.status === 1) {
					// 成功获取数据
					if (response.data && Array.isArray(response.data)) {
						// 处理接口返回的数据，转换为页面需要的格式
						this.contactList = response.data.map(item => {
							const userInfo = item.showUserInfo || {};
							const avatar = userInfo.user_head || '/static/default_avatar.jpg';
							return {
								id: item.friendid, // 使用friendid作为联系人ID
								name: userInfo.nickname || '未知用户',
								avatar: avatar,
								phone: '', // 接口中没有手机号信息，保持空值
								originalData: item // 保存原始数据，以防后续需要
							};
						});
					} else {
						this.contactList = [];
					}
				} else {
					// 获取失败
					uni.showToast({
						title: response.message || '获取联系人列表失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('获取联系人列表失败:', error);
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
			} finally {
				uni.hideLoading();
			}
		},

		// 确认创建群聊
		async confirmCreateGroup() {
			if (this.selectedContacts.length < 2) {
				uni.showToast({
					title: '请至少选择2个联系人',
					icon: 'none'
				});
				return;
			}

			if (!this.groupName.trim()) {
				uni.showToast({
					title: '请输入群聊名称',
					icon: 'none'
				});
				return;
			}

			try {
				// 显示加载提示
				uni.showLoading({
					title: '创建群聊中...'
				});

				// 获取用户信息
				let userInfo = uni.getStorageSync('userInfo');
				const userid = userInfo?.data?.userid || userInfo?.userid || '';

				if (!userid) {
					uni.hideLoading();
					uni.showToast({
						title: '用户信息获取失败',
						icon: 'none'
					});
					return;
				}
				// 构建请求参数
				const requestData = {
					userid: userid,
					name: this.groupName.trim(),
					userlist: this.selectedContacts.map(contact => contact.id).join(',')
				};
				// 调用创建群聊接口
				const response = await this.$Request.postApi('/bot/api/agentccreategroup', requestData);
				// 隐藏加载提示
				uni.hideLoading();
				if (response.status === 1) {
					// 创建成功
					uni.showToast({
						title: response.message || '群聊创建成功',
						icon: 'none'
					});

					// 关闭弹窗
					this.hideCreateGroupModal();

					// 重置表单
					this.groupName = '';
					this.selectedContacts = [];

					// 刷新消息列表，显示新创建的群聊
					setTimeout(() => {
						this.loadMessageList();
					}, 500); // 延迟半秒刷新，确保服务器数据已更新

				} else {
					// 创建失败
					uni.showToast({
						title: response.message || '群聊创建失败',
						icon: 'none'
					});
				}
			} catch (error) {
				// 隐藏加载提示
				uni.hideLoading();
				console.error('创建群聊失败:', error);
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
			}
		},

		// ========== 消息同步相关方法 ==========

		// 启动消息同步 - 添加智能轮询机制
		startMessageSync() {
			this.stopMessageSync(); // 先停止之前的定时器

			// 立即执行一次同步
			this.syncMessages();

			// 然后设置定时器，使用自适应间隔
			this.setupAdaptiveSync();
		},

		// 停止消息同步
		stopMessageSync() {
			if (this.syncTimer) {
				clearInterval(this.syncTimer);
				this.syncTimer = null;
			}
		},

		// 同步消息（增量更新）
		async syncMessages() {
			try {
				// 获取用户信息
				let userInfo = uni.getStorageSync('userInfo');
				const userid = userInfo?.data?.userid || userInfo?.userid || '';

				if (!userid) return;

				// 调用同步接口
				const response = await this.$Request.postApi('/bot/api/agentcgetuserimmsg', {
					userid: userid,
					// _t: Math.floor(Date.now() / 30000) // 30秒内使用同一个时间戳减少不必要的缓存刷新
				});

				if (response.status === 1 && response.data) {
					// 智能比较数据，只在有变化时更新
					const shouldUpdate = this.shouldUpdateMessageList(response.data);

					if (shouldUpdate) {
						this.lastMessageData = JSON.parse(JSON.stringify(response.data));
						this.refreshMessageList(response.data);
					}

					// 更新同步时间
					this.lastSyncTime = Date.now();
				}
			} catch (error) {
				console.error('消息同步失败:', error);
			}
		},

		// 新方法：判断是否需要更新消息列表
		shouldUpdateMessageList(newData) {
			// 第一次加载，直接更新
			if (!this.lastMessageData) return true;

			// 长度不同，需要更新
			if (this.lastMessageData.length !== newData.length) return true;

			// 检查关键字段是否有变化
			for (let i = 0; i < newData.length; i++) {
				const newItem = newData[i];
				const oldItem = this.lastMessageData.find(item => item.id === newItem.id);

				// 新消息或消息内容/红点状态变化
				if (!oldItem ||
					oldItem.new_message !== newItem.new_message ||
					oldItem.show_red !== newItem.show_red ||
					oldItem.show_friendred !== newItem.show_friendred) {
					return true;
				}
			}

			// 好友红点状态变化
			const oldFriendRedDot = this.lastMessageData.some(item => item.show_friendred === 1);
			const newFriendRedDot = newData.some(item => item.show_friendred === 1);
			if (oldFriendRedDot !== newFriendRedDot) return true;

			// 无实质变化
			return false;
		},

		// 处理新消息 - 优化更新逻辑
		handleNewMessages(newMessages) {
			if (!newMessages || newMessages.length === 0) return;

			// 使用优化后的刷新方法
			this.refreshMessageList(newMessages);
			this.showNewMessageNotification();
		},

		// 新方法：设置自适应同步定时器
		setupAdaptiveSync() {
			this.syncTimer = setInterval(() => {
				// 检查页面是否处于活跃状态，调整同步策略
				if (this.isPageActive) {
					this.syncMessages();
				} else {
					// 页面不活跃时，每隔3次轮询才同步一次
					if ((this.refreshFlag % 3) === 0) {
						this.syncMessages();
					}
				}
			}, this.syncInterval);
		},

		// 新方法：设置页面可见性监听
		setupVisibilityListener() {
			// #ifdef H5
			document.addEventListener('visibilitychange', this.handleVisibilityChange);
			// #endif

			// #ifdef APP-PLUS
			plus.globalEvent.addEventListener('resume', () => {
				this.isPageActive = true;
				// 恢复时立即同步一次
				this.syncMessages();
			});

			plus.globalEvent.addEventListener('pause', () => {
				this.isPageActive = false;
			});
			// #endif
		},

		// 新方法：处理页面可见性变化
		handleVisibilityChange() {
			if (document.visibilityState === 'visible') {
				this.isPageActive = true;
				// 页面变为可见时立即同步一次
				this.syncMessages();
			} else {
				this.isPageActive = false;
			}
		},

		// 格式化消息（复用现有逻辑）
		formatMessage(item) {
			const formatDate = (timestamp) => {
				if (!timestamp) return '2025/01/15';
				const date = new Date(timestamp * 1000);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			};

			return {
				id: item.id,
				title: item.name || '智能体名称',
				date: formatDate(item.create_time),
				avatar: item.avatar || '/static/default_avatar.png',
				avatarLoaded: true, // 已加载状态
				hasRedDot: item.show_red === 1,
				description: item.new_message,
				show_friendred: item.show_friendred || 0
			};
		},

		// 检查好友申请红点
		checkFriendRedDot() {
			// 直接使用API返回的原始数据判断
			this.showFriendRedDot = this.messageList.some(item => item.show_friendred === 1);
		},

		// 显示新消息通知
		showNewMessageNotification() {
			// 可以在这里添加新消息提示，比如震动、声音等
			// #ifdef APP-PLUS
			if (this.isPageActive) {
				// 页面活跃时显示Toast提示
				uni.showToast({
					title: '收到新消息',
					icon: 'none',
					duration: 1500
				});
			}
			// #endif
		},

		// 智能同步策略
		startSmartSync() {
			this.stopMessageSync();

			// 根据页面状态调整同步频率
			if (this.isPageActive) {
				this.syncInterval = 2500; // 活跃时2.5秒
			}
			this.syncTimer = setInterval(() => {
				this.syncMessages();
			}, this.syncInterval);
		},

		// 检测用户活跃状态
		detectUserActivity() {
			// 清除之前的定时器
			if (this.userActivityTimer) {
				clearTimeout(this.userActivityTimer);
			}

			// 设置用户为非活跃状态
			this.isPageActive = false;

			// 监听用户操作
			this.userActivityTimer = setTimeout(() => {
				this.isPageActive = true;
				this.startSmartSync(); // 重新启动同步
			}, 30000); // 30秒无操作后认为用户活跃
		},

		// 监听用户操作
		onUserInteraction() {
			this.detectUserActivity();
		},

		// 绑定用户交互事件
		bindUserInteractionEvents() {
			// #ifdef H5
			document.addEventListener('touchstart', this.onUserInteraction);
			document.addEventListener('click', this.onUserInteraction);
			document.addEventListener('scroll', this.onUserInteraction);
			// #endif

			// #ifdef APP-PLUS
			// APP端可以通过触摸事件监听
			// 这里可以添加APP特有的交互监听
			// #endif
		},

		// 解除用户交互事件绑定
		unbindUserInteractionEvents() {
			// #ifdef H5
			document.removeEventListener('touchstart', this.onUserInteraction);
			document.removeEventListener('click', this.onUserInteraction);
			document.removeEventListener('scroll', this.onUserInteraction);
			// #endif
		},

		// 新方法：更新消息已读状态到服务器
		async updateMessageReadStatus(messageId) {
			try {
				let userInfo = uni.getStorageSync('userInfo');
				const userid = userInfo?.data?.userid || userInfo?.userid || '';

				if (!userid || !messageId) return;

				// 这里应该调用更新已读状态的接口，如果有的话
				// 如果没有专门的接口，可以在下次同步时自动处理
			} catch (error) {
				console.error('更新消息已读状态失败:', error);
			}
		},

		// 新方法：直接从响应数据刷新整个消息列表
		refreshMessageList(responseData) {
			if (!responseData || !Array.isArray(responseData) || responseData.length === 0) {
				this.messageList = [];
				this.showFriendRedDot = false;
				return;
			}

			// 检查好友红点状态
			const newFriendRedDot = responseData.some(item => item.show_friendred === 1);
			if (this.showFriendRedDot !== newFriendRedDot) {
				this.showFriendRedDot = newFriendRedDot;
			}

			// 优化DOM更新，先处理所有数据再一次更新DOM
			const newList = responseData.map(item => this.formatMessage(item));

			// 高效地更新列表
			this.updateMessageListEfficiently(newList);
		},

		// 高效地更新消息列表
		updateMessageListEfficiently(newList) {
			// 批量替换消息列表
			this.$nextTick(() => {
				// 使用Vue的批量更新机制
				this.messageList = newList;

				// 只在必要时增加刷新标志
				this.refreshFlag++;
			});
		},
	},

}
</script>

<style>
/* page {
	background-color: #100d05;
} */
</style>

<style lang="scss" scoped>
.page-container {
	width: 100%;
	overflow-y: hidden;
	background-color: #100d05;
	color: #fff;
	height: 100vh;
	position: relative;
}

.main-sroll-view {
	width: 100%;
	// background-color: #100d05;
	/* 移动端滚动优化 */
	-webkit-overflow-scrolling: touch;
	/* iOS滚动优化 */
	scroll-behavior: smooth;
	/* 平滑滚动 */
	padding-top: 0;
	box-sizing: border-box;
}

// 导航栏
.status-bar {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 999;
	background-color: #100d05;
	display: flex;
	align-items: center;
	color: #fff;
	font-weight: 500;
	font-size: 35rpx;
	color: #fff;

	.nav-bar {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.navbar-left {
			width: 60rpx;
			height: 60rpx;
		}

		.navbar-title {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 35rpx;
			font-weight: 500;
		}

		.navbar-right {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			padding-right: 30rpx;

			.nav-icon {
				width: 50rpx;
				height: 50rpx;
			}
		}
	}
}

// 搜索框
.search-container {
	padding: 0 30rpx;
	margin-top: 20rpx;
	margin-bottom: 30rpx;

	.search-box {
		display: flex;
		align-items: center;
		background-color: rgba(255, 255, 255, 0.1);
		border-radius: 40rpx;
		padding: 16rpx 30rpx;
		margin-bottom: 20rpx; // 添加底部间距

		.search-icon {
			width: 38rpx;
			height: 38rpx;
			margin-right: 20rpx;
		}

		.search-input {
			flex: 1;
			height: 48rpx;
			line-height: 48rpx;
			font-size: 28rpx;
			color: #fff;

			&::placeholder {
				color: rgba(255, 255, 255, 0.5);
			}
		}

		.clear-icon {
			width: 29rpx;
			height: 29rpx;
			margin-left: 20rpx;
		}
	}
}

// 消息列表容器
.message-list-container {
	padding: 0 30rpx;
	padding-bottom: 120rpx; // 添加足够的底部间距，确保最后一项可以完全显示
	min-height: 100%;
}

// 消息列表
.message-list {
	// background-color: #100d05; // 确保列表有背景色
	/* 移动端滚动性能优化 */
	-webkit-overflow-scrolling: touch;

	.message-item {
		display: flex !important; // 强制显示
		align-items: center;
		padding: 30rpx 0;
		border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
		/* 移动端滚动性能优化 */
		-webkit-transform: translateZ(0);
		transform: translateZ(0);

		&:last-child {
			border-bottom: none;
			margin-bottom: 40rpx; // 最后一项添加适当的底部间距
		}

		// 头像包装器
		.message-avatar-wrapper {
			position: relative;
			width: 84rpx;
			height: 84rpx;
			border-radius: 50%;
			margin-right: 30rpx;
			flex-shrink: 0;
			background-color: #2c2c2e; // 确保头像有背景色

			.message-avatar {
				width: 100%;
				height: 100%;
				border-radius: 50%;
				background-size: cover;
				background-position: center;
				background-repeat: no-repeat;
				background-color: #2c2c2e;
				opacity: 0;
				/* 初始不可见 */
				transition: opacity 0.3s ease-in-out;

				&.loaded {
					opacity: 1;
				}
			}

			.red-dot {
				position: absolute;
				top: 0; // 调整位置
				right: 32px; // 调整位置
				width: 20rpx; // 调整大小
				height: 20rpx; // 调整大小
				background-color: #ff4757; // 红色
				border-radius: 50%;
				z-index: 999; // 确保在最上层
			}

			.hidden-avatar-image {
				position: absolute;
				top: -9999px;
				left: -9999px;
				width: 1px;
				height: 1px;
				opacity: 0;
				pointer-events: none;
			}

			// 加载动画
			.avatar-loading {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				background: #2c2c2e;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				z-index: 1;
				transition: opacity 0.3s ease-out;

				.avatar-loading-spinner {
					width: 32rpx;
					height: 32rpx;
					border: 2rpx solid rgba(0, 123, 255, 0.2);
					border-top: 2rpx solid #007bff;
					border-radius: 50%;
					animation: spin 0.8s linear infinite;
				}
			}

			// 骨架屏占位符
			.avatar-skeleton {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				background: #2c2c2e;
				border-radius: 50%;
				animation: shimmer 1.5s infinite;
				z-index: 0;

				.avatar-skeleton-shimmer {
					width: 100%;
					height: 100%;
					background: inherit;
					border-radius: 50%;
				}
			}
		}

		// 消息内容
		.message-content {
			flex: 1;
			display: flex;
			flex-direction: column;
			justify-content: center;
			min-width: 0; // 防止内容溢出

			.message-title-row {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-bottom: 16rpx;

				.message-title {
					flex: 1;
					font-size: 32rpx;
					color: #fff;
					font-weight: 600;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
					margin-right: 20rpx;
				}

				.message-date {
					font-size: 24rpx;
					color: rgba(255, 255, 255, 0.5);
					font-weight: 400;
					flex-shrink: 0;
				}
			}

			.message-desc {
				font-size: 28rpx;
				color: rgba(255, 255, 255, 0.7);
				font-weight: 400;
				line-height: 1.4;
				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-line-clamp: 1;
				-webkit-box-orient: vertical;
			}
		}
	}
}

// 加载更多
.loading-more {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 40rpx 0;

	.loading-spinner {
		width: 60rpx;
		height: 60rpx;
		border: 4rpx solid rgba(0, 123, 255, 0.2);
		border-top: 4rpx solid #007bff;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin-bottom: 20rpx;
	}

	.loading-text {
		font-size: 28rpx;
		color: rgba(255, 255, 255, 0.5);
	}
}

// 无数据状态
.empty-message {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;

	.empty-img {
		width: 180rpx;
		height: 120rpx;
		margin-bottom: 40rpx;
		opacity: 0.5;
	}

	.empty-text {
		font-size: 28rpx;
		color: rgba(255, 255, 255, 0.5);
		text-align: center;
	}
}

// 动画
@keyframes spin {
	0% {
		transform: rotate(0deg);
		opacity: 0.8;
	}

	50% {
		opacity: 1;
	}

	100% {
		transform: rotate(360deg);
		opacity: 0.8;
	}
}

@keyframes shimmer {
	0% {
		background-position: -200% 0;
	}

	100% {
		background-position: 200% 0;
	}
}

// 弹窗动画
@keyframes fadeIn {
	from {
		opacity: 0;
	}

	to {
		opacity: 1;
	}
}

@keyframes slideIn {
	from {
		opacity: 0;
		transform: translateY(-20rpx) scale(0.95);
	}

	to {
		opacity: 1;
		transform: translateY(0) scale(1);
	}
}

// 适配不同平台
/* #ifdef APP-PLUS */
.message-item {
	padding: 20rpx 0;
}

.message-avatar-wrapper {
	width: 128rpx;
	height: 128rpx;
}

/* 移动端滚动优化 */
.main-sroll-view {
	-webkit-overflow-scrolling: touch;
	overscroll-behavior: contain;
}

/* 删除安卓和iOS固定位置样式，改用JS动态设置 */
/* 安卓设备弹窗菜单特殊处理 */
.android-popup {
	// 安卓设备不需要特殊处理
}

.android-content {
	// 删除固定top值
	right: 20rpx; // 安卓设备菜单位置
}

.android-arrow {
	right: 18rpx; // 安卓设备调整箭头位置
}

/* iOS设备弹窗菜单特殊处理 */
.ios-popup {
	// iOS设备不需要特殊处理
}

.ios-content {
	// 删除固定top值
	right: 16rpx; // iOS设备菜单位置
}

.ios-arrow {
	right: 24rpx; // iOS设备保持原有箭头位置
}

/* 通用弹窗菜单样式优化 */
.popup-menu {
	/* 确保在不同设备上都有良好的触摸体验 */
	touch-action: none;
	-webkit-touch-callout: none;
	-webkit-user-select: none;
	user-select: none;
}

.popup-content {
	/* 确保弹窗内容在不同设备上都有正确的尺寸 */
	// min-width: 250rpx;
	max-width: 300rpx;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.3);
}

/* #endif */

/* #ifdef MP-WEIXIN */
.message-item {
	padding: 28rpx 0;
}

.message-avatar-wrapper {
	width: 116rpx;
	height: 116rpx;
}

/* #endif */

/* #ifdef H5 */
.message-item {
	padding: 30rpx 0;
}

.message-avatar-wrapper {
	width: 120rpx;
	height: 120rpx;
}

/* #endif */


// 弹窗菜单
.popup-menu {
	// position: fixed;
	// top: 51px;
	// left: 0;
	// right: 0;
	// bottom: 0;
	// // background-color: rgba(0, 0, 0, 0.5);
	// // z-index: 1000;
	// display: flex;
	// justify-content: flex-end;
	// padding-top: 120rpx; // 调整顶部间距，确保弹窗在plus图标下方
	// animation: fadeIn 0.2s ease-out;
	position: fixed;
	top: 30px;
	left: 0;
	right: 0;
	bottom: 0; // 覆盖整个屏幕
	z-index: 1100;
	display: flex;
	justify-content: flex-end;
	margin-top: 0; // 从顶部开始
	animation: fadeIn 0.2s ease-out;

	// 遮罩层样式
	.popup-mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.1); // 半透明背景
	}
}

.popup-content {
	position: absolute;
	// top: v-bind(popupTopPosition); // 使用:style代替
	right: 16rpx; // 右侧固定位置
	background-color: #2c2c2e;
	border-radius: 20rpx;
	padding: 10rpx 0;
	width: 250rpx; // 固定宽度
	animation: slideIn 0.2s ease-out;

	// 弹窗箭头
	.popup-arrow {
		position: absolute;
		top: -20rpx;
		// right: v-bind(arrowRightPosition); // 使用:style代替
		width: 0;
		height: 0;
		border-left: 20rpx solid transparent;
		border-right: 20rpx solid transparent;
		border-bottom: 20rpx solid #2c2c2e;
	}

	// 菜单项
	.menu-item {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 24rpx 30rpx;
		transition: background-color 0.2s ease;

		&:active {
			background-color: rgba(255, 255, 255, 0.1);
		}

		&:not(:last-child) {
			border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
		}

		.menu-icon {
			width: 40rpx;
			height: 40rpx;
			margin-right: 10px;
		}

		.group-chat-icon {
			margin-left: -23rpx;
		}

		.menu-text {
			color: #fff;
			font-size: 28rpx;
			font-weight: 400;
		}

		.menu-red-dot {
			position: absolute;
			top: -5rpx;
			left: -5rpx;
			width: 16rpx;
			height: 16rpx;
			background-color: #ff4757; // 红色
			border-radius: 50%;
			z-index: 2; // 确保在图标之上
		}
	}
}

// 添加好友输入框弹窗
.add-friend-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 1200; // 确保在弹窗菜单和消息列表之上
	background-color: rgba(0, 0, 0, 0.6);
	display: flex;
	align-items: center;
	justify-content: center;
	animation: fadeIn 0.2s ease-out;
}

.add-friend-content {
	background-color: #2c2c2e;
	border-radius: 20rpx;
	width: 90%;
	max-width: 282px;
	padding: 40rpx;
	box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.3);
	animation: slideIn 0.2s ease-out;

	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
		position: relative; // 添加相对定位
		height: 60rpx; // 设置固定高度

		.modal-title {
			position: absolute; // 绝对定位
			left: 50%; // 左偏移50%
			top: 50%; // 顶部偏移50%
			transform: translate(-50%, -50%); // 向左和向上偏移自身50%，实现完全居中
			font-size: 36rpx;
			font-weight: 600;
			color: #fff;
			white-space: nowrap; // 防止标题换行
			z-index: 1; // 确保标题在最上层
		}

		.close-btn {
			position: absolute; // 绝对定位
			right: -7px; // 右对齐
			top: 5%; // 顶部偏移50%
			transform: translateY(-50%); // 向上偏移自身50%，实现垂直居中
			width: 60rpx;
			height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 40rpx;
			color: #fff;
			opacity: 0.7;
			transition: opacity 0.2s ease;
			z-index: 2; // 确保关闭按钮在最上层

			&:active {
				opacity: 1;
			}
		}
	}

	.modal-body {
		margin-bottom: 40rpx;

		.input-group1 {
			display: flex;
			align-items: center;
		}

		.input-group {
			.input-label {
				font-size: 28rpx;
				color: rgba(255, 255, 255, 0.7);
				margin-bottom: 16rpx;
				display: block;
			}

			.phone-input {
				width: 100%;
				height: 80rpx;
				line-height: 80rpx;
				font-size: 28rpx;
				color: #fff;
				background-color: rgba(255, 255, 255, 0.1);
				border: 1rpx solid rgba(255, 255, 255, 0.2);
				border-radius: 40rpx;
				padding: 0 30rpx;
				box-sizing: border-box;
				transition: border-color 0.2s ease;

				&:focus {
					border-color: #007bff;
				}

				&::placeholder {
					color: rgba(255, 255, 255, 0.5);
				}
			}

			.error-tip {
				font-size: 24rpx;
				color: #ff6b6b;
				margin-top: 12rpx;
				padding-left: 30rpx;
			}
		}
	}

	.modal-footer {
		display: flex;
		justify-content: center;

		.confirm-btn {
			width: 100%;
			height: 80rpx;
			background-color: #007bff;
			color: #fff;
			font-size: 32rpx;
			font-weight: 600;
			border-radius: 40rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border: none;
			outline: none;
			transition: all 0.2s ease;

			&.disabled {
				background-color: rgba(0, 123, 255, 0.5);
				color: rgba(255, 255, 255, 0.7);
				cursor: not-allowed;
			}

			&:not(.disabled):active {
				background-color: #0056b3;
				transform: scale(0.98);
			}
		}
	}
}

// 创建群聊弹窗
.create-group-content {
	padding: 40rpx;
	height: 100%;
	display: flex;
	flex-direction: column;

	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		// margin-bottom: 30rpx;
		position: relative;
		// min-height: 120rpx;
		box-sizing: border-box;
		padding: 0 30rpx 0rpx;

		.safe-area-top {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			height: env(safe-area-inset-top);
		}

		.modal-title {
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%, -50%);
			font-size: 36rpx;
			font-weight: 600;
			color: #fff;
			white-space: nowrap;
			z-index: 1;
			line-height: 1;
		}

		.close-btn {
			position: absolute;
			right: -7px;
			top: 50%;
			transform: translateY(-50%);
			width: 60rpx;
			height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 40rpx;
			color: #fff;
			opacity: 0.7;
			transition: opacity 0.2s ease;
			z-index: 2;

			&:active {
				opacity: 1;
			}
		}
	}

	.modal-body {
		flex: 1;
		margin-bottom: 20rpx;
		margin-top: 30rpx;
		overflow: hidden;
		display: flex;
		flex-direction: column;

		.input-group {
			margin-bottom: 30rpx;

			.input-label {
				font-size: 28rpx;
				color: rgba(255, 255, 255, 0.7);
				margin-bottom: 16rpx;
				display: block;
			}

			.group-name-input {
				width: 100%;
				height: 80rpx;
				line-height: 80rpx;
				font-size: 28rpx;
				color: #fff;
				background-color: rgba(255, 255, 255, 0.1);
				border: 1rpx solid rgba(255, 255, 255, 0.2);
				border-radius: 40rpx;
				padding: 0 30rpx;
				box-sizing: border-box;
				transition: border-color 0.2s ease;

				&:focus {
					border-color: #007bff;
				}

				&::placeholder {
					color: rgba(255, 255, 255, 0.5);
				}
			}
		}

		.contact-list-section {
			flex: 1;
			display: flex;
			flex-direction: column;
			min-height: 0; // 确保flex子元素可以收缩

			.section-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;
				padding-bottom: 16rpx;
				border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);

				.section-title {
					font-size: 28rpx;
					color: #fff;
					font-weight: 500;
				}

				.selected-count {
					font-size: 24rpx;
					color: rgba(255, 255, 255, 0.7);
					font-weight: 400;
				}
			}

			.contact-list {
				flex: 1;
				overflow-y: auto;
				height: 0; // 关键：设置高度为0，让flex:1正确工作
				min-height: 0; // 确保flex子元素可以收缩


				.contact-item {
					display: flex;
					align-items: center;
					padding: 20rpx 0;
					border-bottom: 1rpx solid rgba(255, 255, 255, 0.05);
					-webkit-transform: translateZ(0);
					transform: translateZ(0);

					&:last-child {
						border-bottom: none;
					}

					.radio-btn {
						width: 40rpx;
						height: 40rpx;
						border: 2rpx solid rgba(255, 255, 255, 0.3);
						border-radius: 50%;
						display: flex;
						align-items: center;
						justify-content: center;
						margin-right: 20rpx;
						flex-shrink: 0;
						transition: all 0.2s ease;

						&.selected {
							border-color: #007bff;
							background-color: #007bff;
						}

						.radio-inner {
							width: 100%;
							height: 100%;
							display: flex;
							align-items: center;
							justify-content: center;
							border-radius: 50%;

							.checkmark {
								color: #fff;
								font-size: 24rpx;
								font-weight: bold;
								line-height: 1;
							}
						}
					}

					.contact-avatar {
						width: 80rpx;
						height: 80rpx;
						border-radius: 50%;
						margin-right: 20rpx;
						flex-shrink: 0;
						overflow: hidden;
						background-color: #2c2c2e;

						.avatar-img {
							width: 100%;
							height: 100%;
							border-radius: 50%;
						}
					}

					.contact-info {
						flex: 1;
						display: flex;
						flex-direction: column;
						justify-content: center;
						min-width: 0;

						.contact-name {
							font-size: 28rpx;
							color: #fff;
							font-weight: 500;
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
						}

						.contact-phone {
							font-size: 24rpx;
							color: rgba(255, 255, 255, 0.7);
							margin-top: 4rpx;
						}
					}
				}
			}
		}
	}

	.modal-footer {
		padding-top: 10rpx;
		// border-top: 1rpx solid rgba(255, 255, 255, 0.1);

		.confirm-btn {
			width: 100%;
			height: 80rpx;
			background-color: #007bff;
			color: #fff;
			font-size: 32rpx;
			font-weight: 600;
			border-radius: 40rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border: none;
			outline: none;
			transition: all 0.2s ease;

			&.disabled {
				background-color: rgba(0, 123, 255, 0.5);
				color: rgba(255, 255, 255, 0.7);
				cursor: not-allowed;
			}

			&:not(.disabled):active {
				background-color: #0056b3;
				transform: scale(0.98);
			}
		}
	}
}

.menu-icon-wrapper {
	position: relative;
	display: inline-block;

	.menu-red-dot {
		position: absolute;
		top: -5rpx;
		left: -5rpx;
		width: 16rpx;
		height: 16rpx;
		background-color: #ff4757; // 红色
		border-radius: 50%;
		z-index: 2; // 确保在图标之上
	}
}
</style>